package com.cy.pj.sys.web.controller;

import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.common.util.PageUtil;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/user/")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("login/{username}/{password}")
    public JsonResult doLogin(@PathVariable String username,@PathVariable String password){
        //控制层拿到用户名、密码，将信息提交给Shiro
        //通过Subject提交
        //如何获取Subject？
        Subject subject= SecurityUtils.getSubject();
        //如何提交用户和密码（subject对象的login方法）
        //login对象需要UsernamePasswordToken参数类型
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        //设置cookie为持久cookie
        token.setRememberMe(true);
        subject.login(token);//提交给
        // shior的Security Manager
        return new JsonResult("Login ok");
    }

    @PatchMapping("{id}/{valid}")//更新少量数据
    public JsonResult doValidById(@PathVariable/*传值*/ Integer id,@PathVariable Integer valid){
        sysUserService.validById(id, valid);
        return new JsonResult("update ok");
    }

    @RequiresPermissions("sys:user:update")
    @PutMapping
    public JsonResult doUpdateUser(@RequestBody/*传对象*/ SysUser sysUser){
        sysUserService.updateUser(sysUser);
        return new JsonResult("update ok");
    }
    @GetMapping("{id}")
    public JsonResult doFindUserById(@PathVariable Integer id){
        return new JsonResult(sysUserService.findById(id));
    }

    @RequiresPermissions("sys:user:view")
    @GetMapping
    public JsonResult doFindUsers (SysUser sysUser){
        return new JsonResult(
                ()->sysUserService.findUsers(sysUser));
    }

    @PostMapping
    public JsonResult doSaveUser(@RequestBody SysUser sysUser){
        return new JsonResult(sysUserService.saveUser(sysUser));
    }
}
